import { useEffect, useState, useRef, useCallback } from "react";
import Address, { AddressProps } from "../../../address/address";
import Btn from '@/components/button/Btn';
import ListView from "@/components/list";
import { Popup } from 'antd-mobile';
import { useAppSelector, useAppDispatch } from "@/store";
import { updateAddressShowModel, selectAddress } from '@/store/actions';
import Loadding from "@/components/loadding";

export interface AddressModelProps {
    addressList?: AddressProps[];
}

const defaultProps = {
    addressList: [
        {
            selected: false,
            addressId: '1',
            name: '张三',
            phone: '12345678901',
            addressDetail: '广东省深圳市南山区',
            isDefault: true
        },
        {
            selected: false,
            addressId: '3',
            name: '张三',
            phone: '12345678901',
            addressDetail: '河南省123445'
        }
    ]
}

const AddressModel: React.FC<AddressModelProps> = (props) => {
    const {
        addressList,
    } =
    {
        ...defaultProps,
        ...props
    };

    const dispatch = useAppDispatch();
    const showAddressModel = useAppSelector(state => state.address.showAddressModel);
    const addressId = useAppSelector(state => state.address.selectedAddress.addressId);

    const [isLoading, setIsLoading] = useState<boolean>(false);

    const timer = useRef<any>();

    const cancel = useCallback(() => {
        if (timer.current) {
            clearTimeout(timer.current);
            timer.current = null;
        }
    }, []);

    const mergeAddress = () => {
        const newMap = new Map<string, AddressProps>();
        addressList?.map((item) => {
            newMap.set(String(item.addressId), item);
        });
        // 回显地址
        if (addressId) {
            const selectedAddress = newMap.get(String(addressId));
            if (selectedAddress) {
                selectedAddress.selected = true;
            }
        }
        return newMap;
    }

    const [addressListMap, setAddressMap] = useState(mergeAddress);

    const onSelectHandler = (value: { id: string | number, selected: boolean }) => {
        const { id, selected } = value;
        if (isLoading) {
            return;
        }

        setIsLoading(true);

        const address = addressListMap.get(String(id));
        if (address && selected) {
            dispatch(selectAddress(address));
        }

        cancel();
        timer.current = setTimeout(() => {
            setIsLoading(false);
            if (selected) {
                closeShowModel();
            }
        }, 800);
    };

    useEffect(() => {

        return () => {
            cancel();
        };
    }, []);

    const getAddress = (item: AddressProps) => {
        return (
            <>
                <Address {...item} />
            </>
        )
    }

    const closeShowModel = () => {
        dispatch(updateAddressShowModel(false));
    };

    return (
        <Popup visible={showAddressModel}
            showCloseButton
            closeOnSwipe
            closeOnMaskClick
            bodyStyle={{ height: '80%' }}
            onClose={() => {
                closeShowModel()
            }}
            onMaskClick={() => {
                closeShowModel()
            }}>
            <div className='seal-address-scroll' style={{}}>
                <div className="seal-address-header">
                    选择地址
                </div>

                <div className="seal-body">
                    <ListView isSelectOpen onSelected={onSelectHandler}>
                        {
                            Array.from(addressListMap)?.map(([key, addressItem]) => {
                                return (
                                    <ListView.Item
                                        key={key}
                                        id={addressItem.addressId}
                                        children={getAddress(addressItem)}
                                        isChecked={addressItem.selected}
                                    />
                                );
                            })
                        }

                    </ListView>
                </div>

                <div className='seal-footer'>
                    <Btn btnTitle={'新增收货地址'}></Btn>
                </div>

                <Loadding visible={isLoading} />
            </div>
        </Popup>
    )

};

export default AddressModel;